import React, { useState, useEffect, useRef } from 'react';

const ChatComponent: React.FC = () => {
    interface ChatMessage {
        sender: string;
        content: string;
    }
    // 用于存储用户1输入的消息内容，类型为字符串
    const [user1Message, setUser1Message] = useState<string>('');
    // 用于存储用户2输入的消息内容，类型为字符串
    const [user2Message, setUser2Message] = useState<string>('');
    // 存储用户1接收到的消息列表，类型为ChatMessage数组
    const [user1ReceivedMessages, setUser1ReceivedMessages] = useState<ChatMessage[]>([]);
    // 存储用户2接收到的消息列表，类型为ChatMessage数组
    const [user2ReceivedMessages, setUser2ReceivedMessages] = useState<ChatMessage[]>([]);
    // 使用useRef来存储WebSocket实例，避免重新创建
    const socketUser1 = useRef<WebSocket | null>(null);
    const socketUser2 = useRef<WebSocket | null>(null);

    useEffect(() => {
        // 只在组件挂载时创建WebSocket连接
        if (!socketUser1.current) {
            socketUser1.current = new WebSocket('ws://localhost:3000');
        }
        if (!socketUser2.current) {
            socketUser2.current = new WebSocket('ws://localhost:3000');
        }

        const s1 = socketUser1.current;
        const s2 = socketUser2.current;

        // 用户1的 WebSocket 连接打开时的处理逻辑
        s1.onopen = () => {
            console.log('用户1的WebSocket连接已建立');
        };

        // 用户1的 WebSocket 接收到消息时的处理逻辑，添加类型定义
        s1.onmessage = (event: MessageEvent<string>) => {
            const newMessage: ChatMessage = JSON.parse(event.data);
            setUser1ReceivedMessages((prevMessages: ChatMessage[]) => [...prevMessages, newMessage]);
        };

        // 用户1的 WebSocket 连接关闭时的处理逻辑
        s1.onclose = () => {
            console.log('用户1的WebSocket连接已关闭');
        };

        // 用户2的 WebSocket 连接打开时的处理逻辑
        s2.onopen = () => {
            console.log('用户2的WebSocket连接已建立');
        };

        // 用户2的 WebSocket 接收到消息时的处理逻辑，添加类型定义
        s2.onmessage = (event: MessageEvent<string>) => {
            const newMessage: ChatMessage = JSON.parse(event.data);
            setUser2ReceivedMessages((prevMessages: ChatMessage[]) => [...prevMessages, newMessage]);
        };

        // 用户2的 WebSocket 连接关闭时的处理逻辑
        s2.onclose = () => {
            console.log('用户2的WebSocket连接已关闭');
        };

        return () => {
            // 组件卸载时关闭WebSocket连接
            if (s1) {
                s1.close();
            }
            if (s2) {
                s2.close();
            }
        };
    }, []);

    // 处理用户1发送消息的函数，添加参数类型定义
    const handleUser1SendMessage = () => {
        const message: ChatMessage = {
            sender: 'user1',
            text: user1Message
        };
        if (socketUser1.current && socketUser1.current.readyState === WebSocket.OPEN) {
            socketUser1.current.send(JSON.stringify(message));
            setUser1Message('');
        } else {
            console.log('用户1的WebSocket连接未打开，无法发送消息');
        }
    };

    // 处理用户2发送消息的函数，添加参数类型定义
    const handleUser2SendMessage = () => {
        const message: ChatMessage = {
            sender: 'user2',
            text: user2Message
        };
        if (socketUser2.current && socketUser2.current.readyState === WebSocket.OPEN) {
            socketUser2.current.send(JSON.stringify(message));
            setUser2Message('');
        } else {
            console.log('用户2的WebSocket连接未打开，无法发送消息');
        }
    };

    return (
        <div>
            <h2>用户1聊天界面</h2>
            <div>
                {user1ReceivedMessages.map((message, index) => (
                    <div key={index}>
                        <strong>{message.sender}: </strong>
                        {message.text}
                    </div>
                ))}
            </div>
            <input
                type="text"
                value={user1Message}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setUser1Message(e.target.value)}
            />
            <button onClick={handleUser1SendMessage}>发送消息（用户1）</button>

            <h2>用户2聊天界面</h2>
            <div>
                {user2ReceivedMessages.map((message, index) => (
                    <div key={index}>
                        <strong>{message.sender}: </strong>
                        {message.text}
                    </div>
                ))}
            </div>
            <input
                type="text"
                value={user2Message}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setUser2Message(e.target.value)}
            />
            <button onClick={handleUser2SendMessage}>发送消息（用户2）</button>
        </div>
    );
};

export default ChatComponent;